package top.iflyoung.cim.biz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.iflyoung.cim.biz.entity.ChatLoginStatus;
import top.iflyoung.cim.biz.mapper.ChatLoginStatusMapper;
import top.iflyoung.cim.biz.service.ChatLoginStatusService;
import top.iflyoung.cim.biz.service.ChatRouteInfoService;
import top.iflyoung.cim.biz.service.UserService;
import top.iflyoung.cim.common.util.VerifyUtil;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author liguiyang
 * @description
 * @sine 1.8
 * @date 2021/9/416:44
 **/
@Service("chatLoginStatusService")
public class ChatLoginStatusServiceImpl extends ServiceImpl<ChatLoginStatusMapper, ChatLoginStatus> implements ChatLoginStatusService {
    @Autowired
    private UserService userService;
    @Autowired
    private ChatRouteInfoService chatRouteInfoService;

    /**
     * 上线
     *
     * @param userId
     * @return
     */
    @Transactional
    public boolean login(@NotNull Long userId) throws IllegalArgumentException, NullPointerException {
        if (VerifyUtil.isEmpty(userId)) {
            throw new NullPointerException("userID为空");
        }
        if (VerifyUtil.isEmpty(userService.getById(userId))) {
            throw new IllegalArgumentException("数据库不存在这个用户");
        }
        if (baseMapper.queryStatusList(userId).size() > 0) {
            return true;
        }
        ChatLoginStatus status = new ChatLoginStatus();
        status.setUserId(userId);
        return this.save(status);
    }

    /**
     * 下线
     *
     * @param userId
     * @return
     */
    @Transactional
    public boolean offline(Long userId) throws NullPointerException {
        if (VerifyUtil.isEmpty(userId)) {
            throw new NullPointerException("userID为空");
        }
        //删除登录状态，并清楚路由
        return baseMapper.deleteByUserId(userId) > 0 && chatRouteInfoService.removeByUserId(userId) > 0;
    }

    /**
     * 是否在线
     *
     * @param userId
     * @return
     */
    @Override
    public int getSelfOnlineSize(Long userId) {
        return baseMapper.queryCountStatusByUserId(userId);
    }

    public List<ChatLoginStatus> getStatus(Long userid){
        return baseMapper.queryStatusList(userid);
    }
}
